package com.eryos.android.cigarettecounter.widget;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.eryos.android.cigarettecounter.CigaretteCounter;
import com.eryos.android.cigarettecounter.R;
import com.eryos.android.cigarettecounter.database.CigaretteDatabase;
import com.eryos.android.cigarettecounter.io.Preferences;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2012 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

public class UpdateWidgetService extends Service {

	private static final String LOG_TAG = "UpdateWidgetService";
	public static final String INCREASE_ACTION = "com.eryos.android.cigarettecounter.APPWIDGET_INCREASE";

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(LOG_TAG, "Start Service");

		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());

		int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
		
		// Retrieve data from DB
		CigaretteDatabase db = CigaretteDatabase.getInstance(this.getApplicationContext());
		db.open();
		int today = -1;
		if ( db != null ){
			Log.d(LOG_TAG, "init DB OK");
			today = db.getDailyAdapter().getDailyCount();
			//db.close();
		}
		
		Uri widgetLightUri = updateWidgetLight(today);
		
		// For each widget defined
		for (int widgetId : allWidgetIds) {
			Log.i(LOG_TAG, "Widget : " + widgetId);

			// Retrieve the view
			RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.widget_layout);
			
			// Update text and light
			remoteViews.setTextViewText(R.id.widgetValue, String.valueOf(today));
			remoteViews.setImageViewUri(R.id.widgetLight, widgetLightUri);

			// Register an onClickListener
			remoteViews.setOnClickPendingIntent(R.id.widgetButton, CigaretteCounterWidger.createClickPendingIntent(this.getApplicationContext(), allWidgetIds)); //pendingIntent);
 
			appWidgetManager.updateAppWidget(widgetId, remoteViews);
		}
		stopSelf();

		super.onStart(intent, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}


	/**
	 * Method used to define the color of the 'light' based on the daily counter
	 * @param dailyCount : Number of cigarette smoked on the day
	 * @return
	 */
	private Uri updateWidgetLight(int dailyCount){
		try {
			Preferences pref = new Preferences(this.getApplicationContext().getSharedPreferences(CigaretteCounter.PREFS_NAME, 0));
			pref.readParamFromFile();
			int low = pref.getMediumUsageLow();
			int high = pref.getMediumUsageHigh();

			int lightID = R.drawable.no_light;
			if ( dailyCount <= low ){
				// Low
				Log.i(LOG_TAG, "Low Usage");
				lightID = R.drawable.green_light;
			}else if ( dailyCount > high ){
				// High
				Log.i(LOG_TAG, "High Usage");
				lightID = R.drawable.red_light;
			}else {
				// Meidum
				Log.i(LOG_TAG, "Medium Usage");
				lightID = R.drawable.yellow_light;
			}
			return Uri.parse("android.resource://com.eryos.android.cigarettecounter/" + lightID);

		} catch (Exception e) {
			Log.e(LOG_TAG, "updateWidgetLight", e);
			return Uri.parse("android.resource://com.eryos.android.cigarettecounter/" + R.drawable.no_light);
		}
	}
}
